<?php 
//fonction SERVER
function list_server($page){
		//partie html affichage/suppression des serveurs existants
		$sql_query=mysql_query("Select id,name,address,pin from ".DATABASE_TABLE_SERVER." ORDER BY `name` ASC") or die(mysql_error());
		echo '<div id="div_list_server">';
			echo '<form action= "index.php?page='.$page.'" method="post">';
			echo '<table>';
			echo '<caption>List of servers</caption>';
			echo '<tr>';
				echo '<td class="title" colspan="2">';
					echo 'Nom du partage';
				echo'</td>';
				echo'<td class="title">';
					echo 'Adresse du serveur';
				echo'</td>';
				echo'<td class="title">';
					echo 'Code pin du serveur';
				echo'</td>';
			echo '</tr>';
			$i=0;
				while ($query = mysql_fetch_array($sql_query) ){
				$i=1;
				echo '<tr>';
					echo '<td>';
					echo '<input type="checkbox" name="server_box[]" value="'.$query['id'].'">';
					echo '</td>';
					echo'<td>';
					echo $query['name'];
					echo'</td>';
					echo'<td>';
					echo $query['address'];
					echo'</td>';
					echo'<td style="color:#FFFFFF" bgcolor="#FFFFFF" onmouseout="this.bgColor=\'#FFFFFF\';" onmouseover="this.bgColor=\'#DADADA\';">';
					echo $query['pin'];
					echo'</td>';
				echo '</tr>';
				}
			
			echo '<input type="hidden" name="hidden" value="server_remove">';
			if ($i==1){
				echo '<tr>';
				echo '<td colspan="4"><input type="submit" value="Supprimer" /></td>';
				echo '</tr>';
			}
			echo '</table>';
			echo '</form>';
		echo '</div>';
	}

function list_user($page){
//partie html affichage/suppression des users existants
		$sql_query=mysql_query("Select login,access,last_connect,id from ".DATABASE_TABLE_USER." ORDER BY `login` ASC") or die(mysql_error());
		echo '<div id="div_list_server">';
			echo '<form action= "index.php?page='.$page.'" method="post">';
			echo '<table>';
			echo '<caption>List of users</caption>';
			echo '<tr>';
				echo '<td></td><td class="title">';
					echo 'Login';
				echo'</td>';
				echo'<td class="title">';
					echo 'Access';
				echo'</td>';
				echo'<td class="title">';
					echo 'Last connection';
				echo'</td>';
			echo '</tr>';
			$i=0;
			while ($query = mysql_fetch_array($sql_query) ){
				$i=1;
				echo '<tr>';
					echo '<td>';
					echo '<input type="checkbox" name="user_box[]" value="'.$query['id'].'">';
					echo '</td>';
					echo'<td>';
					echo $query['login'];
					echo'</td>';
					echo'<td>';
					echo $query['access'];
					echo'</td>';
					echo'<td>';
					echo $query['last_connect'];
					echo'</td>';
				echo '</tr>';
			}
			echo '<input type="hidden" name="hidden" value="user_remove">';
			if ($i==1){
				echo '<tr>';
				echo '<td colspan="4"><input type="submit" value="Supprimer" /></td>';
				echo '</tr>';
			}
			echo '</table>';
			echo '</form>';
		echo '</div>';
	
}

function add_server($name,$address,$pin){
		//log
		add_log("Ajout d'un server",$name);
		$name = mysql_real_escape_string(htmlspecialchars($name));
		$address = mysql_real_escape_string(htmlspecialchars($address));
		$pin = mysql_real_escape_string(htmlspecialchars($pin));

		mysql_query("INSERT INTO ".DATABASE_TABLE_SERVER."(name,address,pin) VALUES('$name', '$address','$pin')") or die(mysql_error());
	}

function add_user($login,$password,$access){
		//log
		add_log("Ajout d'un user : ".$login);
		$login = mysql_real_escape_string(htmlspecialchars($login));
		$password = md5($password);
		if ($access == "0" or $access =="1" or $access =="2"){
			$access = mysql_real_escape_string(htmlspecialchars($access));
		}else{
			$access = "0";
		}
		
		
		mysql_query("INSERT INTO ".DATABASE_TABLE_USER." VALUES(LAST_INSERT_ID() ,'$login', '$password','$access',NULL)") or die(mysql_error());
	}
	
function remove_server($box){

		$tablength = count($box);
		$i = 0;
		while ($i!=$tablength)
		{
			//log
			add_log("remove d'un server",$box[$i]);
			$sql_query=mysql_query("SELECT name FROM ".DATABASE_TABLE_SERVER." WHERE id = $box[$i] ORDER BY `name` ASC") or die(mysql_error());
			while ($query = mysql_fetch_array($sql_query) ){
				mysql_query("DELETE FROM ".DATABASE_TABLE_FILE." WHERE `server` = '".$query['name']."' ") or die(mysql_error());
			}
			mysql_query("DELETE FROM ".DATABASE_TABLE_SERVER." WHERE `id` = $box[$i]") or die(mysql_error());
			$i++;
		}
	}

function remove_user($box){
		
		$tablength = count($box);
		$i = 0;
		while ($i!=$tablength)
		{
			//log
			$sql_query = mysql_query("SELECT login FROM ".DATABASE_TABLE_USER." WHERE `id` = $box[$i]") or die(mysql_error());
			while ($query = mysql_fetch_array($sql_query) ){
				add_log("remove d'un user : ".$query['login']);	
			}
			
			mysql_query("DELETE FROM ".DATABASE_TABLE_USER." WHERE `id` = $box[$i]") or die(mysql_error());
			$i++;
		}
	}

function file_in_array($server){
		$sql_query=mysql_query("Select name,address,pin from ".DATABASE_TABLE_SERVER." WHERE name like \"".$server."\" ORDER BY `id` ASC") or die(mysql_error());
		$j=0;
		while ($query = mysql_fetch_array($sql_query)){
			if (check_serv_up($query['address']) != "-1"){	
				
				$f=@fopen($query['address']."?serv_request=".md5($query['pin']),'r');
				if ($f != False){
					$e="";
					$i=0;
					while (strpos($e,"<version>") == "" and strpos($e,"<filesearch>")=="" and $i<10){
						$e=fgets($f);
						$i++;
					}
					$e=trim($e);
					$version = substr($e,(strpos($e,"<version>")+9),(strpos($e,"</version>")-9));
					$arrayser = substr($e,(strpos($e,"<filesearch>")+12),(strpos($e,"</filesearch>")-36));
					$array_file=unserialize($arrayser);
					if (! $array_file){
						$_SESSION['error'] = "ERREUR Sur client ".$query['name'];
						
					}
					else{
						if($version=="0.0.1"){
							for ($i=0;$i<count($array_file);$i++){
								$all_array_file[$j][0]=mysql_escape_string($array_file[$i][0]);
								$all_array_file[$j][1]=mysql_escape_string($array_file[$i][1]);
								$all_array_file[$j][2]=mysql_escape_string($array_file[$i][2]);
								$j++;
							}	
						}
						else{
							//print"client invalide";exit();
						}
					}
				}
			}	
		}
		if (count($all_array_file)==0){
			return false;
		}
		else{
			return $all_array_file;
		}
}

function mise_en_forme_address($address){
	if (substr($address,0,7)=="http://"){
			$address=substr($address,7);
		}
	if (strpos($address,"/") != false){
		$address = substr($address,0,strpos($address,"/"));
	}
	
	return $address;
}

function check_serv_up($address){
	
	$address=mise_en_forme_address($address);
	$time_start = microtime(TRUE);
	if( @fsockopen( $address, 80, &$errno, &$errstr, 1) ){
		$time_end = microtime(TRUE);
		$ping = round(($time_end - $time_start)*1000);
	}
	else{
		$ping = -1;
	}
	return $ping;
}

function disconnect_user(){
	//log
	add_log("disconnect user");
	
	$_SESSION['active'] = 0;
	$_SESSION['user'] = false;
	
	//session_destroy();
}

function refresh_server($server){
	//log
	add_log("refresh d'un server",$server);
	//fonction
	$server=mysql_real_escape_string(htmlspecialchars($server));
	
		if ($server == "%"){
			$sql_query=mysql_query("Select name from ".DATABASE_TABLE_SERVER." ORDER BY `name` ASC") or die(mysql_error());
			while ($query2 = mysql_fetch_array($sql_query) ){
				$array=file_in_array($query2['name']);
				if (! $array){
					
				}
				else{
					$sql_query2=mysql_query("DELETE FROM ".DATABASE_TABLE_FILE." WHERE server=\"".$query2['name']."\" ");
					for ($i=0;$i<count($array);$i++){
						$sql_query2=mysql_query("INSERT INTO ".DATABASE_TABLE_FILE."(name,taille,date,server) VALUES('".mysql_real_escape_string($array[$i][0])."', '".mysql_real_escape_string($array[$i][1])."','".mysql_real_escape_string($array[$i][2])."','".mysql_real_escape_string($query2['name'])."')") or die(mysql_error());
					}
				}
			}
		}
		else{
			$array=file_in_array($server);
			if (! $array){
				exit();
			}
			$sql_query=mysql_query("DELETE FROM ".DATABASE_TABLE_FILE." WHERE server=\"".$server."\" ");
			for ($i=0;$i<count($array);$i++){
				$sql_query=mysql_query("INSERT INTO ".DATABASE_TABLE_FILE."(name,taille,date,server) VALUES('".mysql_real_escape_string($array[$i][0])."', '".mysql_real_escape_string($array[$i][1])."','".mysql_real_escape_string($array[$i][2])."','".mysql_real_escape_string($server)."')") or die(mysql_error());
				$sql_query=mysql_query("UPDATE ".DATABASE_TABLE_SERVER." SET last_update = '".time()."' WHERE name like '".mysql_real_escape_string($server)."'")  or die ('Erreur : '.mysql_error());
			}
		}
		exit();
	
}

function get_id($server,$user,$md5){
	$sql_query=mysql_query("SELECT address,pin FROM ".DATABASE_TABLE_SERVER." WHERE name like '".$server."' ORDER BY `name` ASC") or die(mysql_error());
		while ($query = mysql_fetch_array($sql_query) ){
			$address=$query['address'];
			$pin = $query['pin'];
		}
		$f=@fopen($address."?action=getid&user=$user&film=".$md5."&hash=".md5($pin),'r');
			if ($f != False){
					$e="";
					$i=0;
					while (strpos($e,"id") == "" and $i<100){
						$e=fgets($f);
						//print $e."  ".$i;
						$i++;
					}
					$e=trim($e);
					$id = substr($e,(strpos($e,"<id>")+4),(strpos($e,"</id>")-4));
					$array_id[0]=$id;
					$array_id[1]=$address;
					//print $id; exit();
					return $array_id;
				}
		return false;
}
function send_id($array_id){
	header('Location: '.$array_id[1].'?id='.$array_id[0]);	
}

//function pour la mise en forme des requetes.
function array_in_where_clause($table,$array){
	$retour= $table." like '%".$array[0]."' ";
	for ($i=1;$i<count($array);$i++){
		$retour = $retour." OR ".$table." like '%".$array[$i]."' ";
	}
	return $retour;
}

function array_in_where_not_clause($table,$array){
	$retour= $table." not like '%".$array[0]."' ";
	for ($i=1;$i<count($array);$i++){
		$retour = $retour." AND ".$table." not like '%".$array[$i]."' ";
	}
	return $retour;
}

function array_in_where_plus_clause($table,$array){
	$retour= "(".$table." like '%".$array[0]."%' )";
	for ($i=1;$i<count($array);$i++){
		$retour = $retour."+ (".$table." like '%".$array[$i]."%') ";
	}
	return $retour;
}

function array_in_where_OR_clause($table,$array){
	$retour= $table." like '%".$array[0]."%' ";
	for ($i=1;$i<count($array);$i++){
		$retour = $retour." OR ".$table." like '%".$array[$i]."%' ";
	}
	return $retour;
}

//fin des fonction requetes


function add_log($action,$server=""){
	$username = mysql_escape_string($_SESSION['user']->login);
	$action = mysql_escape_string($action); 
	$sql_query=mysql_query("INSERT INTO ".DATABASE_TABLE_LOG."(date,action,user,server) VALUES('".time()."', '".$action."','".$username."','".$server."')") or die(mysql_error());
}
?>